package com.softserveinc.lahire.builders;

import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.StringTokenizer;

public class GetRequestBuilder extends RequestBuilder {

	private URL url;

	public void buildHeaders() {
		String line;
		try {
			do {
				line = in.readLine();
				StringTokenizer tok = new StringTokenizer(line);
				String chunk = (String) tok.nextElement();

				if (chunk.equalsIgnoreCase("Host:")) {
					request.setHost((String) tok.nextElement());

					url = new URL("http://" + request.getHost()
							+ request.getUrl());
					break;
				}

			} while (line != null && line.trim().length() > 0);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public void buildParameters() {
		String query = url.getQuery();

		if (query != null) {

			String[] pair = query.split("&");
			HashMap<String, String> parameters = new HashMap<String, String>();

			for (String mapping : pair) {
				String[] map = mapping.split("=");
				
				if (map.length < 2) {
					parameters.put(map[0], "");
				} else {
					parameters.put(map[0], map[1]);
				}
			}

			request.setParameters(parameters);
			request.setUrl(url.getPath());

		} else {
			request.setParameters(null);
		}
	}
}
